
package cn.sylinx.horm.model.strategy;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cn.sylinx.horm.config.OrmConfigHolder;
import cn.sylinx.horm.model.anno.Column;
import cn.sylinx.horm.model.cache.ModelFabric;
import cn.sylinx.horm.util.StrKit;

/**
 * 下划线策略
 * 
 * @author han
 *
 */
public class UnderlinedStrategy implements Strategy {

    @Override
    public Map<String, String> createAttrMapping(ModelFabric mf) {

        Map<String, String> attrMapping = new HashMap<String, String>();

        Map<String, String> rawAttrMapping = createRawAttrMapping(mf);
        for (Map.Entry<String, String> entry : rawAttrMapping.entrySet()) {
            attrMapping.put(entry.getKey(), entry.getValue());
            if (!OrmConfigHolder.isCaseSensitive()) {
                attrMapping.put(entry.getKey().toUpperCase(), entry.getValue().toUpperCase());
            }
        }

        return attrMapping;
    }

    @Override
    public Map<String, String> createRawAttrMapping(ModelFabric mf) {

        Map<String, String> rawAttrMapping = new HashMap<String, String>();
        List<Field> fields = mf.getFields();
        Map<String, Column> fieldDescMap = mf.getFieldDesc();

        for (Field f : fields) {

            String attr = f.getName();
            String column = convertUnderline(f.getName());

            Column cd = fieldDescMap.get(attr);
            if (cd != null && StrKit.isNotBlank(cd.column())) {
                // 数据库字段不为空
                column = cd.column();
            }

            rawAttrMapping.put(attr, column);
        }

        return rawAttrMapping;
    }

    private String convertUnderline(String attrName) {
        return StrKit.enCodeUnderlined(attrName);
    }
}
